var util = require('../../utils/util.js');
var api = require('../../config/api.js');
var user = require('../../utils/user.js');

var app = getApp();

Page({
 data: {
  cartGoods: [],
  cartTotal: {
   "goodsCount": 0,
   "goodsAmount": 0.00,
   "checkedGoodsCount": 0, //数量
   "checkedGoodsAmount": 0.00, //金额
  },
  isEditCart: false, 
  checkedAllStatus: true,
  editCartList: [],
  hasLogin: false
 },
 onLoad: function(options) {
  // 页面初始化 options为页面跳转所带来的参数
 },
 onReady: function() {
  // 页面渲染完成
 },
 onPullDownRefresh() {
  wx.showNavigationBarLoading() //在标题栏中显示加载
  this.getCartList();
  wx.hideNavigationBarLoading() //完成停止加载
  wx.stopPullDownRefresh() //停止下拉刷新
 },
 onShow: function() {
  // 页面显示
  if (app.globalData.hasLogin) {
  
   this.getCartList();
    this.setData({
      isEditCart:false
    })
    // this.updateData(cartList, cTotal, that.isCheckedAll());
  }

  this.setData({
   hasLogin: app.globalData.hasLogin,
    checkedAllStatus: this.isCheckedAll(),
  });

 },
 onHide: function() {
  // 页面隐藏
 },
 onUnload: function() {
  // 页面关闭
 },
 //更新页面数据
  updateData(cartList, cTotal,method){
    console.log('method:'+method);
   this.setData({
     cartGoods: cartList,
     cartTotal: cTotal,
     checkedAllStatus: method,
   });
 },
 goLogin() {
  wx.navigateTo({
   url: "/pages/auth/login/login"
  });
 },
 goBuy(){
   wx.switchTab({
     url: "/pages/catalog/catalog"
   });
 },
 getCartList: function() {
  let that = this;
  let cartList=wx.getStorageSync('data');
 
  for(let i=0;i<cartList.length-1;i++){
    let temp=cartList[i];
    if(parseInt(cartList[i].id) > parseInt(cartList[i+1].id)){
      cartList[i]=cartList[i+1];
      cartList[i+1]=temp;
      console.log(cartList[i]+">"+cartList[i+1]);
    }
  }
   console.log("---------list----");
   console.log(cartList);
   console.log("-----list------");
  let t= that.calTotal(cartList);
  //  let total=0;//选中的总数量
  //  let totalMoney=0;//选中商品的总金额
  //  for(let i=0;i<cartList.length;i++){
  //    total += cartList[i].num;
  //    totalMoney += cartList[i].num * cartList[i].retailPrice;
  //  }
   
   let cTotal={
     "goodsCount": 0,
     "goodsAmount": 0.00,
     "checkedGoodsCount": t.total, //数量
     "checkedGoodsAmount": t.totalMoney, //金额
   }
   that.updateData(cartList, cTotal,that.isCheckedAll());
  //  that.setData({
  //    cartGoods: cartList,
  //    cartTotal: cTotal,
  //    checkedAllStatus: that.isCheckedAll(),
  //  });
  // util.request(api.CartList).then(function(res) {
  //  if (res.errno === 0) {
  //   that.setData({
  //    cartGoods: res.data.cartList,
  //    cartTotal: res.data.cartTotal
  //   });

  //   that.setData({
  //    checkedAllStatus: that.isCheckedAll()
  //   });
  //  }
  // });
 },
 isCheckedAll: function() {
   console.log("hi,我已经进入了全选判断环节");
  //判断购物车商品已全选
   if (this.data.cartGoods.length==0){
     return false;
   }
  return this.data.cartGoods.every(function(element, index, array) {
  //  if (element.checked == true) {
  //   return true;
  //  } else {
  //   return false;
  //  }
    console.log('element.checked');
    console.log(element.checked)
    return element.checked == true;
  });
 },
 //暂时没用到
 doCheckedAll: function() {
  let checkedAll = this.isCheckedAll()
  this.setData({
   checkedAllStatus: this.isCheckedAll()
  });
 },
 //检验某个商品是否被选中
 checkedItem: function(event) {
  let itemIndex = event.target.dataset.itemIndex;
  let that = this;
  let cartList = that.data.cartGoods;
  let ctotal=that.data.cartTotal;
   let isCheck = cartList[itemIndex].checked;
   cartList[itemIndex].checked = isCheck = !isCheck;
   if (isCheck) {
     ctotal.checkedGoodsCount += cartList[itemIndex].num;
     ctotal.checkedGoodsAmount += cartList[itemIndex].num * cartList[itemIndex].retailPrice;
   } else {
     ctotal.checkedGoodsCount -= cartList[itemIndex].num;
     ctotal.checkedGoodsAmount -= cartList[itemIndex].num * cartList[itemIndex].retailPrice;
   }
   ctotal.checkedGoodsAmount = Math.round(ctotal.checkedGoodsAmount * 100) / 100
   console.log("商品总金额：" + ctotal.checkedGoodsAmount)
   that.updateData(cartList, ctotal, that.isCheckedAll());
   wx.setStorageSync('data', cartList)
  // let productIds = [];
  // productIds.push(that.data.cartGoods[itemIndex].productId);
  // if (!this.data.isEditCart) {
  //   cartList[itemIndex].checked= isCheck = !isCheck;
  //   if(isCheck){
  //     ctotal.checkedGoodsCount += cartList[itemIndex].num;
  //     ctotal.checkedGoodsAmount += cartList[itemIndex].num * cartList[itemIndex].retailPrice;
  //   }else{
  //     ctotal.checkedGoodsCount -= cartList[itemIndex].num;
  //     ctotal.checkedGoodsAmount -= cartList[itemIndex].num * cartList[itemIndex].retailPrice;
  //   }
  //   that.updateData(cartList, ctotal, that.isCheckedAll());
    // that.setData({
    //   cartGoods: cartGoods,
    //   cartTotal: total,
    //   checkedAllStatus: that.isCheckedAll()
    // });
    
  //  util.request(api.CartChecked, {
  //   productIds: productIds,
  //   isChecked: that.data.cartGoods[itemIndex].checked ? 0 : 1
  //  }, 'POST').then(function(res) {
  //   if (res.errno === 0) {
  //    that.setData({
  //     cartGoods: res.data.cartList,
  //     cartTotal: res.data.cartTotal
  //    });
  //   }

  //   that.setData({
  //    cartGoods: res.data.cartList,
  //    cartTotal: res.data.cartTotal,
  //    checkedAllStatus: that.isCheckedAll()
  //   });
  //  });
  // } else {
  //  //编辑状态
  //  let tmpCartData = this.data.cartGoods.map(function(element, index, array) {
  //   if (index == itemIndex) {
  //    element.checked = !element.checked;
  //   }

  //   return element;
  //  });

  //  that.setData({
  //   cartGoods: tmpCartData,
  //   checkedAllStatus: that.isCheckedAll(),
  //   'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
  //  });
  // }
 },
 //计算被选择的数量
 getCheckedGoodsCount: function() {
  let checkedGoodsCount = 0;
  this.data.cartGoods.forEach(function(v) {
   if (v.checked === true) {
    checkedGoodsCount += v.number;
   }
  });
  console.log(checkedGoodsCount);
  return checkedGoodsCount;
 },
 //计算被选中商品的总金额和总数量
 calTotal(cartList){
   var total = 0;//选中的总数量
   var totalMoney = 0;//选中商品的总金额
   if(cartList.length==0){
     console.log("nnnnnnnnnnnnnnnnnnnnnnn")
     return { 'total': 0, 'totalMoney': 0 };
   }
   cartList.forEach(function (v) {
     if(v.checked){
       total += v.num;
       totalMoney += v.num * v.retailPrice;
     }
   }) 
   console.log('数量：' + total + "总金额：" + totalMoney);
   return { 'total': total, 'totalMoney': (Math.round(totalMoney*100)/100)};
 },
 //全选
 checkedAll: function() {
  let that = this;
   let cartList = that.data.cartGoods;
   let ctotal = that.data.cartTotal;
   var totalNum=0;
   var totalMoney=0;
   
   //如果有false就把全部改成true，否则不改，如果全部为true时改成全部为false
   if (that.isCheckedAll()) {
     this.data.cartGoods.forEach(function (v) {
       v.checked = false;
     });
   } else {
     this.data.cartGoods.forEach(function (v) {
       v.checked = true;
       totalNum += v.num;
       totalMoney += v.num * v.retailPrice
     });
   }
   ctotal.checkedGoodsCount = totalNum;
   ctotal.checkedGoodsAmount = totalMoney;
   that.updateData(cartList, ctotal, that.isCheckedAll());
   wx.setStorageSync('data', cartList)
  // if (!this.data.isEditCart) {
  //   this.data.cartGoods.forEach(function (v) {
  //     v.checked = !v.checked;
  //     if(v.checked){
  //       totalNum += v.num;
  //       totalMoney += v.num * v.retailPrice
  //     }else{
  //      ctotal.checkedGoodsCount -= v.num;
  //      ctotal.checkedGoodsAmount -= v.num * v.retailPrice
  //     }
  //   });
  //   ctotal.checkedGoodsCount=totalNum;
  //   ctotal.checkedGoodsAmount=totalMoney;
  //   that.updateData(cartList, ctotal, that.isCheckedAll());
    // that.setData({
    //   cartGoods: cartGoods,
    //   cartTotal: total,
    //   checkedAllStatus: that.isCheckedAll()
    // });
  //  var productIds = this.data.cartGoods.map(function(v) {
  //   return v.productId;
  //  });
  //  util.request(api.CartChecked, {
  //   productIds: productIds,
  //   isChecked: that.isCheckedAll() ? 0 : 1
  //  }, 'POST').then(function(res) {
  //   if (res.errno === 0) {
  //    console.log(res.data);
  //    that.setData({
  //     cartGoods: res.data.cartList,
  //     cartTotal: res.data.cartTotal
  //    });
  //   }

  //   that.setData({
  //    checkedAllStatus: that.isCheckedAll()
  //   });
  //  });
  // } else {
  //  //编辑状态
  //  let checkedAllStatus = that.isCheckedAll();
  //  let tmpCartData = this.data.cartGoods.map(function(v) {
  //    v.checked = !v.checked;
  //   return v;
  //  });

  //  that.setData({
  //   cartGoods: tmpCartData,
  //   checkedAllStatus: that.isCheckedAll(),
  //   'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
  //  });
  // }

 },
  //编辑购物车cartGoods
 editCart: function() {
  var that = this;
  if (this.data.isEditCart) {
   let t= this.calTotal(this.data.cartGoods);
   let cartTotal = this.data.cartTotal
    cartTotal.checkedGoodsCount = t.total
    cartTotal.checkedGoodsAmount = t.totalMoney
   this.setData({
    isEditCart: !this.data.isEditCart,
     cartTotal: cartTotal
   });
    console.log('======');
    console.log(that.data.cartGoods);
    wx.setStorageSync('data', this.data.cartGoods);
  } else {
   //编辑状态
  //  let tmpCartList = this.data.cartGoods.map(function(v) {
  //    v.checked = false;
  //   return v;
  //  });
    
   this.setData({
    // editCartList: this.data.cartGoods,
    // cartGoods: tmpCartList,
    isEditCart: !this.data.isEditCart,
    checkedAllStatus: that.isCheckedAll(),
    // 'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
   });
    // console.log(tmpCartList);
  }

 },
 //修改数量并更新购物车信息(没用)
 updateCart: function(productId, goodsId, number, id) {
  let that = this;

  util.request(api.CartUpdate, {
   productId: productId,
   goodsId: goodsId,
   number: number,
   id: id
  }, 'POST').then(function(res) {
   that.setData({
    checkedAllStatus: that.isCheckedAll()
   });
  });

 },
 //减数量
 cutNumber: function(event) {

  let itemIndex = event.target.dataset.itemIndex;
  let cartItem = this.data.cartGoods[itemIndex];
  let number = (cartItem.num - 1 > 1) ? cartItem.num - 1 : 1;
  cartItem.num = number;
  this.setData({
   cartGoods: this.data.cartGoods
  });
  // this.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);
 },
 //加数量
 addNumber: function(event) {
  let itemIndex = event.target.dataset.itemIndex;
  let cartItem = this.data.cartGoods[itemIndex];
   var total = cartItem.brandId - 0;//商品库存
   let number = cartItem.num + 1 >= total ? total : cartItem.num + 1;
   if(total==number){
     wx.showToast({
       title: '亲，库存量已经空了！',
     })
   }
  cartItem.num = number;
  this.setData({
   cartGoods: this.data.cartGoods
  });
  // this.updateCart(cartItem.productId, cartItem.goodsId, number, cartItem.id);

 },
 //下单
 checkoutOrder: function() {
  //获取已选择的商品
  let that = this;
  console.log('*******下单*********')
   console.log(wx.getStorageSync('cartData'))
  var checkedGoods = this.data.cartGoods.filter(function(element, index, array) {
    return element.checked == true && element.num>0;
  });
   console.log(checkedGoods)
   if (checkedGoods.length <= 0) {
     util.showErrorToast('选择下单的商品');
     return false;
   }
   wx.setStorageSync('cartData', checkedGoods)
 

  // storage中设置了cartId，则是购物车购买
  try {
   wx.setStorageSync('cartId', 0);
   wx.navigateTo({
     url: '/pages/checkout/checkout'
   })
  } catch (e) {}

 },
  //删除购物项
 deleteCart: function() {
  //获取已选择的商品
  let that = this;
   let ctotal = that.data.cartTotal;
  //  let cartList = this.data.cartGoods.filter(function (element, index, array) {
  //    return element.checked != true;
  //  });
   let cartList = this.data.cartGoods.map(function(element, index, array){
     if (element.checked){
         element.num=0;
       element.checked = !element.checked;
       }
     return element;
   });
   let t=that.calTotal(cartList);
  //  var total = 0;//选中的总数量
  //  var totalMoney = 0;//选中商品的总金额
  //  cartList.forEach(function (v) {
  //    total += v.num;
  //    totalMoney += v.num * v.retailPrice;
  //  }) 
   ctotal.checkedGoodsCount = t.total;
   ctotal.checkedGoodsAmount = t.totalMoney;
   that.setData({
     cartGoods: cartList,
     cartTotal: ctotal
    });
   wx.setStorageSync('data', cartList);
  // if (productIds.length <= 0) {
  //  return false;
  // }

  // productIds = productIds.map(function(element, index, array) {
  //  if (element.checked == true) {
  //   return element.productId;
  //  }
  // });


  // util.request(api.CartDelete, {
  //  productIds: productIds
  // }, 'POST').then(function(res) {
  //  if (res.errno === 0) {
  //   console.log(res.data);
  //   let cartList = res.data.cartList.map(v => {
  //    v.checked = false;
  //    return v;
  //   });

  //   that.setData({
  //    cartGoods: cartList,
  //    cartTotal: res.data.cartTotal
  //   });
  //  }

  //  that.setData({
  //   checkedAllStatus: that.isCheckedAll()
  //  });
  // });
 }
})